<template>
	<div class="">
		<bread-crumb>賽事結果覆核</bread-crumb>
		<div class="uc-body" v-loading="loading" v-if="this.isSuperUser">
			<!--篩選控制-->
			<div class="manage-list-control">
				<div class="c-blue">本頁面只顯示結果待覆核的投票</div>
				<el-button type="success" size="small" @click="reFresh" >刷新</el-button>
			</div>
			<manage-list
				:data-list="reviewVoteList"
				:timestamp-now="timestampNow"
				@actJumpDetail="actShowDialog"
			>
			</manage-list>
		</div>
		<div class="uc-body" v-else>
			非法用戶
		</div>
		<!--******************************************* 结果填写弹层 ***********************************************-->

		<el-dialog
			title=""
			width="340px"
			top="calc(50vh - 250px)"
			:append-to-body="true"
			:visible.sync="visibleSettle"
			:before-close="onCloseResultWrite"
		>
			<div class="dialog-detail-module">
				<div class="module-title">結果覆核</div>
				<div class="line"></div>
				<div class="module-wrap">
					<div class="v-row">
						<span>參賽隊伍：</span>
						<div class="con">
							{{voteObject.contestMaster}}
							<img src="@/assets/vs.svg" alt="">
							{{voteObject.contestBranch}}
						</div>
					</div>
          <div class="v-row">
            <span>賽事結果：</span>
            <div class="con number f24">
              {{ contestResultFlat(voteObject.sportingInfo.result) }}
            </div>
          </div>

				</div>
				<div class="line"></div>
				<div class="btn-group">
					<el-button
						type="success"
						size="medium"
						icon="el-icon-check" round :loading="submiting" :disabled="submiting"
						@click="actSettleResult(voteObject.proposalId,1)"
					>
						通過
					</el-button>
					<el-button
						type="danger"
						size="medium"
						icon="el-icon-close" round :loading="submiting" :disabled="submiting"
						@click="actSettleResult(voteObject.proposalId,0)"
					>
						不予通過
					</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { mapGetters } from "vuex";
//数据
import manageList from "./components/manageList";
import breadCrumb from '../components/breadCrumb.vue'
import { mixins } from '@/mixins/mixins'
import { mixinsUtils } from '@/mixins/mixins.utils'
import { mixinsManage } from "@/views/manage/js/manage.mixins";
import { contestMixinsGlobal} from '@/views/contestHall/contest.mixins.global'
import {
	tronAllowanceList,
	apiToBeReviewVote,
	tronGetVoteKeyData,
	apiVotingAnalysisServe
} from "@/views/uc/manage/js/manage.user.lib";
import {
	governancePoolContract,
	voteGovernanceContract
} from "@/views/manage/js/manage.lib";
import util from "@/libs/util";
import {tronAdminContestResultCheck, getEffectiveValueForContest3} from "@/views/manage/js/manage.func";
import { allowance, approve, hex2Num } from "@/libs/tron.lib";
import { apiRequestGameTron } from "@/views/contestHall/contest.func";
import { msgInterface, smartContractBroadcastCallback, smartContractConfirmCallback } from "@/libs/site.utils";


const debounce = util.debounce(1000) //初始化个防抖对象

//导出
export default {
	name:"manageContestCheck",
	components: { breadCrumb,manageList },
	mixins:[mixins,mixinsUtils,mixinsManage,contestMixinsGlobal],
	data () {
		return {
			/////////////////////////////////////////////////////////////////
			loading:false,
			visibleSettle: false,//弹层显示
			submiting    : false,//是否提交中
			timestampNow : 0,
			listDataCount: 0,//数量
			//////////////////////////////////////////////////////////////////
			//请求参数
			requestParameter: {
				sender: this.sender
			},
			//数据列表
			reviewVoteList:[],
			//基础数据对象,
			voteObject:{
				sportingInfo:{
					rs:[] //初始化这个值，以免出错
				}
			},
		}
	},
	computed:{
		...mapGetters(['isSuperUser']),
	},
	created () {
		this.pageInit()
	},
	mounted () {
	},
	methods:{
		//初始化
		pageInit(){
			if( this.isSuperUser ) {
				this.getToBeReviewDataList()//加载数据
			} else {
				this.$message.error('非法用户')
			}
		},
		//获取待复核结果的投票列表数据
		getToBeReviewDataList () {
			let that = this;
			apiToBeReviewVote({
				...this.requestParameter
			}, (res) => {
				if (res.resultFlag) {
					this.listDataCount  = res.count
					this.reviewVoteList = res.data
					let _idArr =  this.reviewVoteList.reduce((ret,cur) => {
						ret.push(cur.sportingId)
						return ret
					},[])
					// that.viewProposalInfo(_idArr, this.reviewVoteList);

				}
			})
		},

		//请求实时数据，并解析
		viewProposalInfo(param, manageList) {
			let that = this;
			//从赛事合约请求实时数据并解析
			tronGetVoteKeyData(param).then((rs) => {
				//解析合约返回（目前使用服务器的接口来解析）
				apiRequestGameTron({
					"type": 1,
					'act': 'returnDataAnalyze',
					"param": rs
				}).then(result => {
					let data = result;
					if (data.resultFlag != true) {
						return;
					}
					let splitData = data.data.splitList[0];

				}).catch(err => {
					console.log(err)
				})
			});
		},

		/**
		 * 复核提交处理
		 * @param proposalId 投票id
		 * @param type 类型
		 */
		actSettleResult (proposalId,type) {
			let sender = this.sender
			let that = this
			let _tip = type== 1 ? '通過' : '駁回' //标题
			let _act = type== 1 ? 1 : 0 //动作,这里作为提交的直接数据，可能要看实际情况再改

			this.$confirm('確定要'+_tip+'結果嗎?', '提示', {
				confirmButtonText: '確定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.visibleSettle = false //关闭对话框
				//todo 这个标题要适合多游戏
				const ACTION = that.LangSet(['复核:', 'check:'])
				const ACTION_TITLE = `${that.voteObject.contestMaster}vs${this.voteObject.contestBranch}(${that.voteObject.infoName})游戏结果`
				msgInterface('結果複核', 0, 1);//等待钱包确认
				that.funcAllowance().then(function (rs) {
					//对复审投票审核
					tronAdminContestResultCheck(
						that.voteObject.sportingId,
						100000000,
						_act,
						that.sender,
						smartContractBroadcastCallback(ACTION, ACTION_TITLE, (status, txid) => {
							that.submiting = false //恢复可提交
							if (status == 1) {
								apiVotingAnalysisServe({}, txid); //通知服务器根据hash爬新数据
								setTimeout(() => {
									that.getToBeReviewDataList()//加载数据
								},5000)
								setTimeout(() => {
									that.getToBeReviewDataList()//加载数据
								},10000)
							}
						}),
						smartContractConfirmCallback(ACTION, ACTION_TITLE)
					)
				}).catch(()=>{
					this.$notify({ title: '警告', message: '授權失敗', type: 'warning' });
				})

			}).catch(() => {

			});
		},

		/**
		 * //todo 待测试
		 * 授权，由于基于基础币，所以授权的是基础币
		 * @returns {Promise<unknown>}
		 */
		funcAllowance(){
			return new Promise((resolve,reject)=>{
				let _sender = this.sender
				let _token = this.xg.address
				let _decimal = this.xg.decimal
				//先查询是否授权
				allowance(this.xg.address, governancePoolContract, _sender, (res) => {
					let owance = hex2Num(res, _decimal);
					if (owance <= 0) {
						approve(
							governancePoolContract,
							this.xg.address,
							_sender,
							smartContractBroadcastCallback("授權", this.xg.name, (status, txid) => {
								console.log('hash:', txid)
								if (status == 1) {
									resolve();
								}else{
									reject()
								}
							})
						);
					}else if (owance > 0) {
						console.log('已经授权过')
						resolve();
					}
				});
			})
		},

		//授权 这里用了批量授权的方法，改为单个授权的，不用这个
		/*inquiryApprove2(tokens, spender, decimals, sender, user) {
			return new Promise(function (resolve, reject) {
				tronAllowanceList(governancePoolContract, tokens, spender, sender, user, (res) => {
					let _analyzing = getEffectiveValueForContest3(res, 2)
					let counter = 0;
					for (let i = 0; i < _analyzing.length; i++) {
						let owance = _analyzing[i] / Math.pow(10, decimals[i]);
						if (owance <= 0) {
							approve(spender[i], tokens[i], user, (res) => {
								operationResults(res);
								counter++;
								if (res == 1) if (counter == tokens.length) resolve({'code': 1});
							});
						}
						if (owance > 0) counter++;
					}
					if (counter == tokens.length) resolve({'code': 1});
				});
			})
		},*/


		///////////////////////////////////////////////////其它/////////////////////////////////////////////////////
		///////////////////////////////////////////////////其它/////////////////////////////////////////////////////
		///////////////////////////////////////////////////其它/////////////////////////////////////////////////////
		//刷新，筛选
		reFresh () {
			this.showLoading()
			debounce(()=> {
				this.getToBeReviewDataList()
				setTimeout(() => {
					this.hideLoading()
				},100)
			})
		},

		//显示操作层
		actShowDialog(id){
			let that = this;
			this.voteObject = this.reviewVoteList.find((item) => {
				if (parseInt(item.proposalId) == id) {
					that.voteObject = item;
					return item
				}
			})
			this.visibleSettle = true
		},

		//关闭结果填写,如果绑定了关闭回调，则要调用done()
		onCloseResultWrite(done){
			done()
		},
	}
}
</script>

<style lang="less" scoped>
/*公共变量*/
@import '~@/assets/global.less';
//单独控制弹层样式细节
.dialog-detail-module {
	font-size: 16px;
	.module-wrap {
		.v-row {padding:3px 0;}
	}
	.btn-group{
	}
}
/************************************适应***************************************/
@media screen and (max-width: @MINSCREEN){

}
</style>
